<template>
	<s-layout title="限时抢购">
		<!-- <s-empty v-if="state.list.length === 0" text="购物车空空如也,快去逛逛吧~" icon="/static/cart-empty.png" /> -->
  <s-empty v-if="state.activity.activityState === 0" text="暂无活动,敬请期待吧~" icon="/static/data-empty.png" />


		<view class="topImabeViw">
			<image class="topImabeViwImave" :src="state.activity.picUrl" mode="scaleToFill" @tap="sheep.$router.go('/pages/index/gz', { description: state.activity.saleRule })"></image>
		</view>
		
		
		
		
		
		<view  class="timeView"  v-if="state.activity.activityState >=1 ">
			
			
			<view>活动时间： {{state.activity.activityTimeTip}}</view>
			
			
		</view>
		<view v-if="state.activity.activityState != 0">
		<view  class="timeView" v-if="startTime.ms <= 0 && endTime.ms > 0  " >
			
			
			<view class="countdown-time ma" >
			               <view class="ss-flex countdown-h">距离结束时间: {{ endTime.h }}</view>
			               <view class="ss-m-x-4">:</view>
			               <view class="countdown-num ss-flex ss-row-center">{{ endTime.m }}</view>
			               <view class="ss-m-x-4">:</view>
			               <view class="countdown-num ss-flex ss-row-center">{{ endTime.s }}</view>
			  </view> 
			
			
		</view>
		</view>
		<!-- 
		
       <s-empty v-if="state.specialSaleProducts.length === 0" text="暂无活动,敬请期待吧~" icon="/static/cart-empty.png" />

		<!-- 头部 -->
		<view class="cart-box ss-flex ss-flex-col ss-row-between"  v-if="state.specialSaleProducts.length != 0" >
			<!-- 内容 -->

			<view class="left15 top12">
				<view class="bgClolor titeltext">
					<text>秒杀商品</text>
				</view>
				<view class="cart-content    bgClolor">
					<view class="goods-box ss-r-10 ss-m-b-14 " v-for="(item,index) in state.specialSaleProducts"
						:key="item.id">
						<view class="ss-flex ss-col-center">
							<label class="check-box ss-flex ss-col-center ss-p-l-10" @tap="onspeSelectSingle(index)">
								<radio :disabled="endTime.ms <= 0" :checked="state.selectedIds.includes(item.skuId)" color="var(--ui-BG-Main)"
									style="transform: scale(0.8)" @tap.stop="onspeSelectSingle(index)" />
							</label>
							<!-- :skuText="item.purchaseMinimum" -->
							<s-goods-item :title="item.spuName" :img="item.picUrl || item.image" :price="item.salePrice"
								@click="sheep.$router.go('/pages/goods/index', { id: item.spuId,isDetail:true })"
								:skuid="item"
								
								:isshowskuid="state.isshowskuid"
								:issnetWeight ="state.issnetWeight"
								:standardPiece="item.standardPiece"
								 priceColor="#FF3000" :titleWidth="400">
								<template v-if="!state.editMode" v-slot:tool>
									<su-number-box :disabled="endTime.ms <= 0"  :min="item.purchaseMinimum" :max="item.purchaseMaximum > -1 ? item.purchaseMaximum : 9999" :step="1" v-model="item.count" @change="onspeNumberChange($event, index)" />
								</template>
							</s-goods-item>
							
							
						</view>
					</view>
					
				</view>
			<!-- 	<view  class="footernumeber">
					还剩
				</view> -->
			</view>

			<!-- 内容 -->
			<view class="left15 top12"  v-if="state.generalProductsList.length != 0">
				<view class="bgClolor titeltext">
					<text>普通商品</text>
				</view>
				<view class="cart-content    bgClolor">
					<view class="goods-box ss-r-10 ss-m-b-14 " v-for="(item,index) in state.generalProductsList"
						:key="item.id">
						<view class="ss-flex ss-col-center">
							<label class="check-box ss-flex ss-col-center ss-p-l-10" @tap="ongenSelectSingle(index)">
								<radio :disabled="endTime.ms <= 0"  :checked="state.selectedIds.includes(item.skuId)" color="var(--ui-BG-Main)"
									style="transform: scale(0.8)" @tap.stop="ongenSelectSingle(index)" />
							</label>
								<!-- // :skuText="item.purchaseMinimum" -->
							<s-goods-item :title="item.spuName" :img="item.picUrl || item.image" :price="item.salePrice"
								@click="sheep.$router.go('/pages/goods/index', { id: item.spuId ,isDetail:true})"
								:skuid="item"
							
								:isshowskuid="state.isshowskuid"
								:issnetWeight ="state.issnetWeight"
								:standardPiece="item.standardPiece"
								 priceColor="#FF3000" :titleWidth="400">
								<template v-if="!state.editMode" v-slot:tool>
									<su-number-box :disabled="endTime.ms <= 0" :min="item.purchaseMinimum" :max="item.purchaseMaximum > -1 ? item.purchaseMaximum : 9999" :step="1" v-model="item.count" @change="ongenNumberChange($event, index)" />
								</template>
							</s-goods-item>
						</view>
					</view>
				</view>
			</view>


			<!-- 底部 -->
			<su-fixed bottom placeholder v-if="state.specialSaleProducts.length > 0" :isInset="true">
				<view class="cart-footer ss-flex ss-col-center ss-row-between ss-p-x-30 border-bottom">
					<view class="footer-left ss-flex ss-col-center">
						<label class="check-box ss-flex ss-col-center ss-p-r-30" @tap="onSelectAll">
							<radio :disabled="endTime.ms <= 0" :checked="state.isAllSelected" color="var(--ui-BG-Main)"
								style="transform: scale(0.8)" @tap.stop="onSelectAll" />
							<view class="ss-m-l-8"> 全选 </view>
						</label>
						<text>合计：</text>
						<view class="text-price price-text">
							{{ fen2yuan(state.totalPriceSelected) }}
						</view>
					</view>
					<view class="footer-right">
						<button v-if="startTime.ms >=0 && state.activity.activityState==1 "  class="ss-reset-button ui-BG-Main-Gradient pay-btn ui-Shadow-Main"
							>
						 <view class="ss-flex countdown-time" >
						                <view class="ss-flex countdown-h">{{ startTime.h }}</view>
						                <view class="ss-m-x-4">:</view>
						                <view class="countdown-num ss-flex ss-row-center">{{ startTime.m }}</view>
						                <view class="ss-m-x-4">:</view>
						                <view class="countdown-num ss-flex ss-row-center">{{ startTime.s }}</view>
						              </view>
						</button>
						<button v-if="(startTime.ms <= 0 && endTime.ms >= 0 ) || (state.activity.activityState==2 && endTime.ms >= 0 ) " class="ss-reset-button ui-BG-Main-Gradient pay-btn ui-Shadow-Main"
							@tap="onConfirm">
							去结算
							{{ state.selectedIds?.length ? `(${state.selectedIds.length})` : '' }}
						</button>
						<button disabled="ture" v-if="state.activity.activityState== 3 || endTime.ms <= 0 " class="ss-reset-button  pay-btn  disabled-color"
							style="background-color: gainsboro; ">
						     已结束
						</button>
						
					</view>
				</view>
			</su-fixed>
		</view>

	</s-layout>
</template>

<script setup>
	import sheep from '@/sheep';
	import {
		onLoad,
		onShow,
		onHide,
		onReachBottom,
		onPageScroll,
		onPullDownRefresh
	} from '@dcloudio/uni-app';
	import {
		computed,
		reactive,
		onMounted
	} from 'vue';
	import {
		fen2yuan,
		useDurationTime
	} from '../../sheep/hooks/useGoods';
	import _ from 'lodash-es';
	import SpuApi from '@/sheep/api/product/spu';
	import CartApi from '@/sheep/api/trade/cart';

	// const sys_navBar = sheep.$platform.navbar;
	// const cart = sheep.$store('cart');

	const state = reactive({

		pagination: {
			list: [],
			total: 0,
			pageNo: 1,
			pageSize: 4,
		},
		list: [],
		activity: {},
		specialSaleProducts: [], //特价商品
		generalProductsList: [], //必买商品
		loadStatus: '',
		selectedList: [],
		selectedIds: [], // 已选列表
		isAllSelected: false, // 是否全选
		totalPriceSelected: 0, // 选中项总金额
		showSelect: false,
		editMode: false,
		isshowskuid:true,
		issnetWeight:true,

	});
  // 倒计时
  const startTime = computed(() => {
    return useDurationTime(state.activity.startTime);
  });
  
  // 倒计时
  const endTime = computed(() => {
    return useDurationTime(state.activity.endTime);
  });
	// 特价单选选中
	function onspeSelectSingle(index) {

		state.specialSaleProducts[index].selected = !state.selectedIds.includes(state.specialSaleProducts[index].skuId),
			state.selectedIds = []
		state.isAllSelected = true;
		state.totalPriceSelected = 0;
		state.specialSaleProducts.forEach((item) => {
			if (item.selected) {
				state.selectedIds.push(item.skuId);
				state.totalPriceSelected += item.count * item.salePrice;

			} else {
				state.isAllSelected = false;
			}

		});

		state.generalProductsList.forEach((item) => {

			if (item.selected) {
				state.selectedIds.push(item.skuId);
				state.totalPriceSelected += item.count * item.salePrice;

			} else {
				state.isAllSelected = false;
			}
		});

	}
	// 必选单选选中
	function ongenSelectSingle(index) {
		
		
		// return

		state.generalProductsList[index].selected = !state.selectedIds.includes(state.generalProductsList[index].skuId),
			state.selectedIds = []
		state.isAllSelected = true;
		state.totalPriceSelected = 0;

		state.generalProductsList.forEach((item) => {

			if (item.selected) {
				state.selectedIds.push(item.skuId);
				state.totalPriceSelected += item.count * item.salePrice;

			} else {
				state.isAllSelected = false;
			}

		});

		state.specialSaleProducts.forEach((item) => {
			if (item.selected) {
				state.selectedIds.push(item.skuId);
				state.totalPriceSelected += item.count * item.salePrice;

			} else {
				state.isAllSelected = false;
			}


		});

	}

	// 全选
	function onSelectAll() {
		// cart.selectAll(!state.isAllSelected);

		state.selectedIds = []

		state.totalPriceSelected = 0;

		state.generalProductsList.forEach((item) => {
			item.selected = !state.isAllSelected
			if (item.selected) {
				state.selectedIds.push(item.skuId);
				state.totalPriceSelected += item.count * item.salePrice;
			}
		});

		state.specialSaleProducts.forEach((item) => {

			item.selected = !state.isAllSelected
			if (item.selected) {
				state.selectedIds.push(item.skuId);
				state.totalPriceSelected += item.count * item.salePrice;
			}

		});

		state.isAllSelected = !state.isAllSelected;
	}

	// 结算
async	function onConfirm() {
	
	

		let items = []
		let goods_list = [];
		
		let gPlist = []
		goods_list  = _.concat(state.specialSaleProducts, state.generalProductsList);
		
		state.selectedList = goods_list.filter((item) => state.selectedIds.includes(item.skuId));
		
		
			
		state.selectedList.map((item) => {
			// 此处前端做出修改
			items.push({
				skuId: item.skuId,
				count: item.count,
				
			})
			
		});	
		const {
			code,
			data,
			msg
		} = await SpuApi.getSpuspecialchasecheck({
			
			"activityId":state.activity.id,
			"skus": items
		});
			
		if (code !== 0) {
			
			sheep.$helper.toast(msg);
			return;
		}
		
		if(data){
			
			sheep.$router.go('/pages/order/confirm', {
				data: JSON.stringify({
					items
				}),
				specialActivityId:state.activity.id
			});
			
		}else{
			
			sheep.$helper.toast(msg);
			
		}
	
	}
	
	
	
	async function getcheckSpuListpurchase(ids) {
	
		const {
			code,
			data
		} = await SpuApi.getSpuListpurchasecheck({
	
			"skus": ids
		});
		
		console.log(data)
		if (code !== 0) {
			return;
		}
	}
	
	async function ongenNumberChange(e, index) {
		
		if(e===state.generalProductsList[index].purchaseMinimum-1){
			
				sheep.$helper.toast('已选商品最小数量');
		   return
		}
		
		
		if(e===state.generalProductsList[index].purchaseMaximum+1){
			
				sheep.$helper.toast('已选商品最大数量');
		   return
		}
		
		
			state.selectedIds = []
		state.totalPriceSelected = 0
		
		state.generalProductsList[index].count = e
		state.generalProductsList.forEach((item) => {
			if (item.selected) {
				state.selectedIds.push(item.skuId);
				state.totalPriceSelected += item.count * item.salePrice;
			}
		});
		
		state.specialSaleProducts.forEach((item) => {
		
			if (item.selected) {
				state.selectedIds.push(item.skuId);
				state.totalPriceSelected += item.count * item.salePrice;
			}
		
		});
	}

	async function onspeNumberChange(e, index) {
		
		if(e===state.specialSaleProducts[index].purchaseMinimum-1){
			
				sheep.$helper.toast('已选商品最小数量');
		   return
		}
		
		if(e===state.specialSaleProducts[index].purchaseMaximum+1){
			
				sheep.$helper.toast('已选商品最大数量');
		   return
		}
			state.selectedIds = []
			state.totalPriceSelected = 0
		
		state.specialSaleProducts[index].count = e
		
		state.specialSaleProducts.forEach((item) => {
		
			if (item.selected) {
				state.selectedIds.push(item.skuId);
				state.totalPriceSelected += item.count * item.salePrice;
			}
		
		});
		
		state.generalProductsList.forEach((item) => {
			if (item.selected) {
				state.selectedIds.push(item.skuId);
				state.totalPriceSelected += item.count * item.salePrice;
			}
		});
		
	}
	async function onDelete() {
		cart.delete(state.selectedIds);
	}

	function onclickdetil(e) {

	}

  onHide(() => {
     
    });

	async function getGoodgsactivity(ids) {


		const {
			code,
			data
		} = await SpuApi.getSpuListactivitydetail({
			
			type:2
		});
		         
			console.log(data,'dddfff')
		if (code !== 0) {
			return;
		}
		
		  console.log(code)
		
		
		state.activity = data
		if(state.activity.activityState===0){
			
			return
		}
	     state.specialSaleProducts = data.specialSaleProducts
	
			state.specialSaleProducts.forEach((item) => {
	        item.selected = false
				// item.selected = true
				item.count = item.purchaseMinimum
				// state.selectedIds.push(item.skuId);
				// state.totalPriceSelected += item.count * item.salePrice;
			});
	
	    	state.generalProductsList = data.generalProducts
			
			state.generalProductsList.forEach((item) => {
	
	item.selected = false
				// item.selected = true
				item.count = item.purchaseMinimum
				// state.selectedIds.push(item.skuId);
				// state.totalPriceSelected += item.count * item.salePrice;
			});
		
	}


async	function getGoodsListSpecialSaleProducts(specialSaleProducts) {

	

	}

	async function getGoodsListGeneralProducts(generalProducts) {

		// state.loadStatus = 'loading';
		const {
			code,
			data
		} = await SpuApi.getSpuListByIds(generalProducts.join(','));
		if (code !== 0) {
			return;
		}

	
		state.generalProductsList = data
		state.generalProductsList.forEach((item) => {

			item.selected = true
			item.count = item.purchaseMinimum
			state.totalPriceSelected += item.count * item.salePrice;
			// if (item.selected) {

			// } else {
			//    state.isAllSelected  = false;
			// }
		});
	}

	// 初始化
	onMounted(async () => {
		console.log('mounted');

		// var dict  =	uni.getStorageSync('userInfo');
		// console.log(userInfo);
		// console.log(uni.getStorageSync('user-store').userInfo.id);
		// console.log(userInfo.value.id);
		getGoodgsactivity();
		// if (layoutType === LayoutTypeEnum.TWO_COL) {
		//   // 分列
		//   calculateGoodsColumn();
		// }
	});
</script>

<style lang="scss" scoped>
	// :deep(.ui-fixed) {
	// 	height: 2rpx;

	// }

	.left15 {

		paddint: 10rpx 20rpx;
		background-color: #f6f6f6;
	}

	.cart-box {
		width: 100%;

		.cart-header {
			height: 70rpx;
			background-color: #f6f6f6;
			width: 100%;
			position: fixed;
			left: 0;
			top: v-bind('sys_navBar') rpx;
			// z-index: 1000;
			box-sizing: border-box;
		}



		.cart-content {
			// margin-top: 70rpx;

			.goods-box {
				background-color: #fff;
			}
		}
	}

	.cart-footer {
		height: 120rpx;
		background-color: #fff;

		.pay-btn {
			width: 180rpx;
			height: 70rpx;
			font-size: 28rpx;
			line-height: 28rpx;
			font-weight: 500;
			border-radius: 40rpx;
		}
	}


	.titeltext {

		font-size: 30rpx;
		font-weight: 900;
		padding: 20rpx 25rpx 10rpx 20rpx;
	}

	.bgClolor {
		background-color: #fff;

	}

	.top12 {

		margin-top: 70rpx;
	}

.footernumeber {
	
	text-align: center;
}
	.topImabeViw {

		height: 220rpx;
		// width:23rpx;
		width: 100%;
		// background-color: yellow;

	}

	.topImabeViwImave {

		height: 188rpx;
		width: 100%;
		// weigth:100%
		// background-color: red;


	}
	
	.timeView {
		margin: auto;
		width: 50%;
		height: 60rpx;
		line-height: 60rpx;
		// background-color: yellow;
		text-align: center;
	}
	
	.ma {
		display: flex;
		    flex-direction: row;
			justify-content: center;
		    align-items: center;
		// background-color: red;
			margin: auto;
		// text-align: center;
	}
</style>